//
//  GZchuliQRmassagerVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/13.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "GZchuliQRmassagerVC.h"
#import "Masonry.h"
#import "ZJSwitch.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "YXKit.h"
#import "MBProgressHUD.h"
#import "GZdataModel.h"
#import "PhotoCollectionCell.h"
#import "PhotoModel.h"
#import "AlbumVC.h"
#import "WorkViewController.h"
#import "PHATextView.h"
static NSString *collectionViewCellIdentf = @"collectionViewCell1";
static CGFloat imageSize = 80;
@interface GZchuliQRmassagerVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextViewDelegate>
{
    
    ZJSwitch *_swi;
    NSInteger state;
    NSString *_timeStr;
    PHATextView *_resultText;
    UILabel *_content1;
    UIButton *_updata;
}
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)NSArray *rigthCount1;
@property (nonatomic,strong)NSArray *rigthCount2;
@property (nonatomic,strong)UIView  *backView4;
@property (nonatomic,strong)NSMutableArray *AllImageUrl;
@property (nonatomic,strong)UIScrollView *scrollView;
@end

@implementation GZchuliQRmassagerVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController setNavigationBarHidden:NO];
    _AllImageUrl = [[NSMutableArray alloc]init];
    for (NSInteger i = 0; i < self.imageArr.count; i++) {
        PhotoModel *model = [[PhotoModel alloc]init];
        model.imageName = self.imageArr[i];
        [_AllImageUrl addObject:model];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"故障处理确认";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *delegate = app.delegate;
    self.username = delegate.username;
    self.userId = delegate.userId;

    state = 0;
    [self initScorlleview];
}
- (void)initScorlleview{
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.frame = CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64);
    self.scrollView.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [self.view addSubview:self.scrollView];
    // 隐藏水平滚动条
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;

    //故障基本信息背景
    UIView *backView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 10, kSCREEN_WIDTH, 50)];
    backView1.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView1];

    //故障基本信息图标 d_icon01   编辑图标d_icon04 大小30*30
    UIImageView *gzMimageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
    gzMimageView.image = [[UIImage imageNamed:@"d_icon01"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [backView1 addSubview:gzMimageView];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(45, 15, 150, 21)];
    title.text = @"故障基本信息";
    title.adjustsFontSizeToFitWidth = YES;
    title.font = [UIFont systemFontOfSize:21.0];
    title.textColor = UIColorFromRGB(0x0093d5);
    [backView1 addSubview:title];
    
    //基本信息详情背景
    UIView *backView2 = [[UIView alloc]initWithFrame:CGRectZero];
    backView2.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView2];

    
    
    NSArray *leftTitle_arr = @[@"故障基站",@"设备名称",@"设备品牌",@"设备型号",@"上报时间"];
    
    
    for (NSInteger i = 0; i < leftTitle_arr.count; ++i) {
        
        
        UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 + i * (21+10), 60, 21)];
        titleName.adjustsFontSizeToFitWidth = YES;
        titleName.font = [UIFont systemFontOfSize:15.0];
        titleName.textColor = UIColorFromRGB(0x4d4d4d);
        titleName.text = leftTitle_arr[i];
        [backView2 addSubview:titleName];
        
        UILabel *content = [[UILabel alloc]initWithFrame:CGRectMake(80, 5 + i * (30+1), kSCREEN_WIDTH/4*3, 30)];
        content.text = self.section1[i];
        content.adjustsFontSizeToFitWidth = YES;
        content.backgroundColor = UIColorFromRGB(0xf0f0f0);
        content.font = [UIFont systemFontOfSize:13.0];
        content.textColor = UIColorFromRGB(0x4d4d4d);
        [backView2 addSubview:content];
        backView2.frame = CGRectMake(0, CGRectGetMaxY(backView1.frame)+2, kSCREEN_WIDTH, CGRectGetMaxY(content.frame)+5);
        
    }
    //故障处理信息
    UIView *backView3 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backView2.frame)+2, kSCREEN_WIDTH, 50)];
    backView3.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView3];

    //故障处理信息图标 d_icon01   编辑图标d_icon04 大小30*30
    UIImageView *gzChuLimageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
    gzChuLimageView.image = [[UIImage imageNamed:@"ic_handle"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [backView3 addSubview:gzChuLimageView];
    
    UILabel *ChuLiTitle = [[UILabel alloc]initWithFrame:CGRectMake(45, 15, 150, 21)];
    ChuLiTitle.text = @"故障处理信息";
    ChuLiTitle.adjustsFontSizeToFitWidth = YES;
    ChuLiTitle.font = [UIFont systemFontOfSize:21.0];
    ChuLiTitle.textColor = UIColorFromRGB(0x0093d5);
    [backView3 addSubview:ChuLiTitle];
    
    //处理信息详情背景

    self.backView4.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.backView4];


    NSArray *leftTitle_arr1 = @[@"处理人员",@"故障级别",@"检修类型",@"停机时长",@"配件跟换",@"处理结果"];
    
    
    for (NSInteger i = 0; i < leftTitle_arr1.count; ++i) {
        
        
        UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 + i * (21+10), 60, 21)];
        titleName.adjustsFontSizeToFitWidth = YES;
        titleName.font = [UIFont systemFontOfSize:15.0];
        titleName.textColor = UIColorFromRGB(0x4d4d4d);
        titleName.text = leftTitle_arr1[i];
        [self.backView4 addSubview:titleName];
        
        _content1 = [[UILabel alloc]initWithFrame:CGRectZero];//CGRectMake(80, 5 + i * (30+1), kSCREEN_WIDTH/4*3, 30)];
        _content1.text = self.section2[i];
        _content1.adjustsFontSizeToFitWidth = YES;
        _content1.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _content1.font = [UIFont systemFontOfSize:13.0];
        _content1.textColor = UIColorFromRGB(0x4d4d4d);
        _content1.numberOfLines = 0;
        CGRect rect = [_content1.text boundingRectWithSize:CGSizeMake(kSCREEN_WIDTH/4*3, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:_content1.font,NSFontAttributeName, nil]  context:nil];
        CGFloat height = rect.size.height;
        _content1.frame = CGRectMake(80, 5 + i * (30+1), kSCREEN_WIDTH/4*3, height+15);
        [self.backView4 addSubview:_content1];
        
    }
    //图片数组中只有一个元素 且这个元素是空字符串 不实例化collectionView
    if (self.imageArr.count == 1 && [self.imageArr[0] length] == 0){
        
        self.backView4.frame = CGRectMake(0, CGRectGetMaxY(backView3.frame)+2, kSCREEN_WIDTH, CGRectGetMaxY(_content1.frame)+5);
    }else{
        
    //图片展示
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(imageSize, imageSize);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_content1.frame)+2, kSCREEN_WIDTH, imageSize + 20) collectionViewLayout:layout];
    
    [collectionView registerClass:[PhotoCollectionCell class] forCellWithReuseIdentifier:collectionViewCellIdentf];
    UINib *nib = [UINib nibWithNibName:@"PhotoCollectionCell" bundle:nil];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"imageCell"];
    collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    [self.backView4 addSubview:collectionView];
    self.backView4.frame = CGRectMake(0, CGRectGetMaxY(backView3.frame)+2, kSCREEN_WIDTH, CGRectGetMaxY(collectionView.frame)+5);
    }

    //处理结果确认
    UIView *backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backView4.frame)+2, kSCREEN_WIDTH, 50)];
    backView5.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView5];

    //故障处理信息图标 d_icon01   编辑图标icon_01012 大小30*30
    UIImageView *ChuLResultimageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
    ChuLResultimageView.image = [[UIImage imageNamed:@"icon_01012"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [backView5 addSubview:ChuLResultimageView];
    
    UILabel *CLresultTitle = [[UILabel alloc]initWithFrame:CGRectMake(45, 15, 150, 21)];
    CLresultTitle.text = @"处理结果确认";
    CLresultTitle.adjustsFontSizeToFitWidth = YES;
    CLresultTitle.font = [UIFont systemFontOfSize:21.0];
    CLresultTitle.textColor = UIColorFromRGB(0x0093d5);
    [backView5 addSubview:CLresultTitle];
    
    //处理信息详情背景
    UIView *backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backView5.frame)+2, kSCREEN_WIDTH, 130)];
    backView6.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView6];
//    [backView6 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(backView5.mas_bottom).offset(2);
//        make.left.equalTo(_scrollView).offset(0);
//        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH,130));
//    }];
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    _timeStr = [dateFormatter stringFromDate:currentDate];
    NSArray *leftTitle_arr2 = @[@"是否确认",@"确认结果"];
    //NSArray *rightC = @[self.username,_timeStr];
    for (NSInteger i = 0; i < leftTitle_arr2.count; ++i) {
        
        if (i == 0) {
            UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 + i * (21+13), 60, 21)];
            titleName.adjustsFontSizeToFitWidth = YES;
            titleName.font = [UIFont systemFontOfSize:15.0];
            titleName.textColor = UIColorFromRGB(0x4d4d4d);
            titleName.text = leftTitle_arr2[i];
            [backView6 addSubview:titleName];
            _swi = [[ZJSwitch alloc]initWithFrame:CGRectMake(80,5 + i * (21+10), 60, 31)];
            _swi.tintColor = [UIColor lightGrayColor];
            _swi.transform = CGAffineTransformMakeScale(0.75, 0.75);
            _swi.onText = @"是";
            _swi.offText = @"否";
            [_swi addTarget:self action:@selector(handleSwitch:) forControlEvents:UIControlEventValueChanged];
            [backView6 addSubview:_swi];
        }else {
            UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 + i * (21+10), 60, 21)];
            titleName.adjustsFontSizeToFitWidth = YES;
            titleName.font = [UIFont systemFontOfSize:15.0];
            titleName.textColor = UIColorFromRGB(0x4d4d4d);
            titleName.text = leftTitle_arr2[i];
            [backView6 addSubview:titleName];
            _resultText = [[PHATextView alloc]initWithFrame:CGRectMake(80, 8 + i * (30+1), kSCREEN_WIDTH/4*3, 80)];
            _resultText.placeholder = @"不超过100个字符";
            
            _resultText.backgroundColor = UIColorFromRGB(0xf0f0f0);
            _resultText.font = [UIFont systemFontOfSize:13.0];
            _resultText.delegate = self;
            _resultText.backgroundColor = [UIColor whiteColor];
            _resultText.layer.borderColor = [[UIColor lightGrayColor] CGColor];
            _resultText.layer.borderWidth = 0.5;
            _resultText.layer.cornerRadius = 3;
            [backView6 addSubview:_resultText];
        }

        
    }
   UIView *backView7 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backView6.frame)+2, kSCREEN_WIDTH, 60)];
    backView7.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView7];

    //提交取消bttuon
    _updata = [UIButton buttonWithType:UIButtonTypeSystem];
    [_updata setTitle:@"提交" forState:UIControlStateNormal];
    [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
    _updata.backgroundColor = UIColorFromRGB(0x2dd500);
    [backView7 addSubview:_updata];
    [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView7).offset(10);
        make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
    }];
    
    UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancerl setTitle:@"取消" forState:UIControlStateNormal];
    [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    cancerl.backgroundColor = UIColorFromRGB(0xd50037);
    [backView7 addSubview:cancerl];
    [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView7).offset(10);
        make.left.equalTo(_updata.mas_right).offset(20);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
    }];
    self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(backView7.frame)+50);

    
}

#pragma mark-->collectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return _AllImageUrl.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
    PhotoModel *model = _AllImageUrl[indexPath.row];
    [cell fillCellWithModel:model];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    AlbumVC *alVC = [[AlbumVC alloc]init];
    alVC.ImageUrl = self.imageArr;
    alVC.index = indexPath.row;
    [self.navigationController pushViewController:alVC animated:YES];
}


- (void)handleSwitch:(ZJSwitch *)sender{

    if (sender.isOn) {
        
        state = 1;
    }else{
        state = 0;
    }
}
- (void)up{

    [UIView animateWithDuration:0 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _updata.userInteractionEnabled = NO;
    } completion:^(BOOL finished) {
        _updata.userInteractionEnabled = YES;
    }];
    if (_resultText.text.length < 1) {
        
        [self showAlert:@"温馨提示" message:@"请完善确认信息" actionWithTitle:@"确定"];
    }else if(_resultText.text.length > 100){
        [self showAlert:@"温馨提示" message:@"确认结果超过限定字数请重新填写" actionWithTitle:@"确定"];
    }else{
    NSDictionary *Parameter = @{orId:[NSString stringWithFormat:@"%ld",self.orID],userid:[NSString stringWithFormat:@"%ld",self.userId],sbState:[NSString stringWithFormat:@"%ld",state],disc:_resultText.text,updataTime:_timeStr};
    //NSLog(@"%@",Parameter);
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_chuliUpdata parameters:Parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        NSInteger status = [dic[@"status"]integerValue];
        NSLog(@"%ld",status);
        if (status == 1) {

            //延时操作
            [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"提交成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                
            } completion:^(BOOL finished) {
                
                [self.navigationController popViewControllerAnimated:YES];
                /*
                //将控制器压入栈，然后去栈中查找
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[WorkViewController class]]) {
                        
                        WorkViewController *work = (WorkViewController *)controller;
                        [self.navigationController popToViewController:work animated:YES];
                    }
                }*/
                
            }];
           

            
        }else{
            
        [self showAlert:@"提交失败" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self showAlert:@"提交失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
    }];
 }
}
- (UIView *)backView4
{
    if (!_backView4) {
        _backView4 = [[UIView alloc]init];
    }
    return _backView4;
}

#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您是否确定退出当前页面" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:OkAction];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
